var express = require('express');
var router = express.Router();
let path = require('path');
let fs = require('fs');
let svg = require('svg-captcha');
const session = require("cookie-session");
const formidable = require('formidable');

/* GET users listing. */
router.get('/register', function (req, res, next) {
  res.render('register')
});

router.use(session({
  keys: ['AFAF']
}))

//验证码
router.get('/yanzm', (req, res) => {
  let captcha = svg.create({
    size: 4,
    noise: 2,
    ignoreChars: '1l0oOI',
    color: true
  });
  req.session.q = captcha.text;
  console.log(req.session);
  res.type('svg');
  res.send(captcha.data);
})

router.post('/register', (req, res, next) => {
  let {
    username,
    password,
    password2,
    yanzm
  } = req.body;

  if (!username || !password || !password2 || !yanzm) {
    next("请输入有效内容")
    return
  }
  //(2)、获取persones.json里面
  let data = JSON.parse(fs.readFileSync(path.join(__dirname, '../persons.json')));
  //(3)、判断账号和密码是否一直，如果一直提示登入成功, 否则账号和密码不一致
  let s = data.find(item => username == item.username);
  if (s) {
    next('用户名已存在')
    return;
  }
  if (password != password2) {
    next("两次密码不一致")
    return
  }

  if (yanzm.toLocaleLowerCase() != req.session.q.toLocaleLowerCase()) {
    next('输入验证码不正确')
    return
  }

  data.push({
    username,
    password
  })
  fs.writeFileSync(path.join(__dirname, "persons.json"), JSON.stringify(data))
  res.render('aa', {
    zhengque: '注册成功'
  })
})

module.exports = router;